window.old_testament = {
    '创世记': ['创', 50],
    '出埃及记': ['出', 40],
    '利未记': ['利', 27],
    '民数记': ['民', 36],
    '申命记': ['申', 34],
    '约书亚记': ['书', 24],
    '士师记': ['士', 21],
    '路得记': ['得', 4],
    '撒母耳记上': ['撒上', 31],
    '撒母耳记下': ['撒下', 24],
    '列王记上': ['王上', 22],
    '列王记下': ['王下', 25],
    '历代志上': ['代上', 29],
    '历代志下': ['代下', 36],
    '以斯拉记': ['拉', 10],
    '尼希米记': ['尼', 13],
    '以斯帖记': ['斯', 10],
    '约伯记': ['伯', 42],
    '诗篇': ['诗', 150],
    '箴言': ['箴', 31],
    '传道书': ['传', 12],
    '雅歌': ['歌', 8],
    '以赛亚书': ['赛', 66],
    '耶利米书': ['耶', 52],
    '耶利米哀歌': ['哀', 5],
    '以西结书': ['结', 48],
    '但以理书': ['但', 12],
    '何西阿书': ['何', 14],
    '约珥书': ['珥', 3],
    '阿摩司书': ['摩', 9],
    '俄巴底亚书': ['俄', 1],
    '约拿书': ['拿', 4],
    '弥迦书': ['弥', 7],
    '那鸿书': ['鸿', 3],
    '哈巴谷书': ['哈', 3],
    '西番雅书': ['番', 3],
    '哈该书': ['该', 2],
    '撒迦利亚': ['亚', 14],
    '玛拉基书': ['玛', 4],
}
window.new_testament = {
    '马太福音': ['太', 28],
    '马可福音': ['可', 16],
    '路加福音': ['路', 24],
    '约翰福音': ['约', 21],
    '使徒行传': ['徒', 28],
    '罗马书': ['罗', 16],
    '哥林多前书': ['林前', 16],
    '哥林多后书': ['林后', 13],
    '加拉太书': ['加', 6],
    '以弗所书': ['弗', 6],
    '腓立比书': ['腓', 4],
    '歌罗西书': ['西', 4],
    '帖撒罗尼迦前书': ['帖前', 5],
    '帖撒罗尼迦后书': ['帖后', 3],
    '提摩太前书': ['提前', 6],
    '提摩太后书': ['提后', 4],
    '提多书': ['多', 3],
    '腓利门书': ['门', 1],
    '希伯来书': ['来', 13],
    '雅各书': ['雅', 5],
    '彼得前书': ['彼前', 5],
    '彼得后书': ['彼后', 3],
    '约翰一书': ['约一', 5],
    '约翰二书': ['约二', 1],
    '约翰三书': ['约三', 1],
    '犹大书': ['犹', 1],
    '启示录': ['启', 22],
}

window.placeholder_info = `请在此处输入...

不必写满七日, 示例如下:

周三
1为我们的属灵生命祷告
2为约书亚团契祷告

请注意,
每日最多可添加4个祷告事项,
每个祷告事项最多40个字.
超出部分将不予显示`

window.onload = () => {
    init_form()
};

function init_form() {

    window.yue1 = document.querySelector("select[name=yue1]")
    window.yue2 = document.querySelector("select[name=yue2]")
    window.juan1 = document.querySelector("select[name=juan1]");
    window.zhang1 = document.querySelector("select[name=zhang1]");
    window.juan2 = document.querySelector("select[name=juan2]");
    window.zhang2 = document.querySelector("select[name=zhang2]");
    window.capacity1 = document.querySelector('select[name=capacity1]')
    window.capacity2 = document.querySelector('select[name=capacity2]')
    window.thisweek = document.querySelector('input#thisweekRadio')
    window.nextweek = document.querySelector('input#nextweekRadio')
    window.textarea_ = document.querySelector("textarea#exampleFormControlTextarea1")
    window.all_select = document.querySelectorAll('select.form-control:enabled')
    window.no_auto_toggle = 1

    yue1.addEventListener('change', yue_on_change)
    yue2.addEventListener('change', yue_on_change)
    juan1.addEventListener('change', juan_on_change)
    juan2.addEventListener('change', juan_on_change)
    thisweek.addEventListener('change', anewday)
    nextweek.addEventListener('change', anewday)

    // 模拟一次点击事件
    yue1.dispatchEvent(new Event('change'))
    yue2.dispatchEvent(new Event('change'))

    //给文本框添加placeholder
    textarea_.setAttribute('placeholder', placeholder_info)

    // 填入每日读经数
    let e_capacity_s = document.querySelectorAll("select[name^=capacity]");
    for (let e_capacity of e_capacity_s) {
        e_capacity.innerText = '';
        for (let i = 1; i <= 5; i++) {
            let e = document.createElement('option');
            e.setAttribute("value", i);
            e.innerText = `每日 ${i} 章`;
            e_capacity.appendChild(e)
        }
    }

    //三个按钮
    document.querySelector("button#btn_adj").addEventListener('click', fill_form)
    document.querySelector("button#btn_clr").addEventListener('click', () => textarea_.value = '')
    document.querySelector("button#btn_fil").addEventListener('click', fil_fun)

    try {
        fill_form()
    }
    catch (e) {
        console.log(e)
    }
}

function shining(e, timeout, duration) {
    // e可能是某个元素, 或者NodeList
    let myInterval
    if (e instanceof Element) {
        myInterval = setInterval(e => e.style.backgroundColor = e.style.backgroundColor == "yellow" ? "white" : "yellow", timeout, e)
    }
    else if (e instanceof NodeList) {
        myInterval = setInterval(e => {
            e.forEach(i => i.style.backgroundColor = i.style.backgroundColor == "yellow" ? "white" : "yellow")
        }, timeout, e)
    }

    if (!myInterval) return

    setTimeout(() => {
        clearInterval(myInterval)
        if (e instanceof Element) {
            e.style.removeProperty('background-color')
        }
        else if (e instanceof NodeList) {
            e.forEach(i => i.style.removeProperty('background-color'))
        }
    }, duration)

}

function __fill_form__(data) {
    shining(all_select, 300, 1200)
    
    juan1.value = data['juan1']
    // 不点击, 直接改value不会自动触发change事件, 需手动触发
    juan1.dispatchEvent(new Event('change'))

    juan2.value = data['juan2']
    juan2.dispatchEvent(new Event('change'))

    setTimeout(() => {
        zhang1.value = data['zhang1']
        zhang2.value = data['zhang2']
    }, 50);

    capacity1.value = data['capacity1']
    capacity2.value = data['capacity2']
    if ('msg' in data) {
        textarea_.value = data['msg']
    }

    if ('date' in data) {
        let date = data['date']
        if (is_in_this_week(date)) {
            //thisweek.checked = true
            thisweek.click()
        } else {
            nextweek.click()
        }
    }
}

async function anewday() {
    if (no_auto_toggle) return

    let data = { 'juan1': juan1.value, 'juan2': juan2.value, 'zhang1': zhang1.value, 'zhang2': zhang2.value, 'capacity1': capacity1.value, 'capacity2': capacity2.value, 'isthisweek': this.value }
    let args = {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
            "Content-Type": "application/json",
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
    }

    let resp = await fetch(`http://${window.location.host}/get_weekly_form_data`, args)
    if (resp.ok) {
        let new_data = await resp.json()
        __fill_form__(new_data)
    }
}

async function fill_form() {
    // 相当于加了一把锁, 防止thisweek和nextweek的触发
    // 本函数只会执行一次, 下一行代码不写也无妨
    no_auto_toggle = 1
    let resp = await fetch(`http://${window.location.host}/get_form_data?fakeid=${Math.ceil(Math.random() * 10000)}`)

    if (resp.ok) {
        let data = await resp.json()
        // Object.keys(data).forEach(k=>console.log(k))
        __fill_form__(data)
    }
    no_auto_toggle = 0
}

function yue_on_change() {

    // e.target/e.srcElement与this同对象
    let testament = this.value === '0' ? old_testament : new_testament
    let juan = this['name'] === 'yue1' ? juan1 : juan2
    juan.innerText = '';
    let entries = Object.entries(testament);
    entries.forEach((item, index) => {
        let e = document.createElement('option');
        e.setAttribute("value", item[0]);
        e.innerText = `${item[0]}（${item[1][0]}）`;
        juan.appendChild(e)
    });

    // juan不会自动触发, 须dispatchEvent
    juan.dispatchEvent(new Event('change'))
}

function juan_on_change() {

    let testament = this.value in old_testament ? old_testament : new_testament
    let zhang = this['name'] === 'juan1' ? zhang1 : zhang2
    zhang.innerHTML = '';
    // let index = juan.selectedIndex;
    // let k = juan.options[index].value
    let num = testament[this.value][1]
    for (let i = 1; i <= num; i++) {
        let e = document.createElement('option');
        e.setAttribute("value", i);
        e.innerHTML = `第 ${i.toString().padStart(3, '0')} 章`;
        zhang.appendChild(e)
    }
}

function is_in_this_week(date) {
    let today = new Date()
    today.setHours(23, 59, 59)
    let today_ms = today.getTime()
    let day2week = today.getDay()
    if (day2week === 0) day2week = 7

    let delta_sunday = (7 - day2week) * 86400000

    let sunday_ms = today_ms + delta_sunday
    let date_ms = Date.parse(date)

    return date_ms <= sunday_ms
}

function fil_fun() {
    textarea_.value = `周一
1为自己的心祷告
2为年轻人的灵魂得救祷告

周二
1为我们有能听的耳、受教的心祷告
2为牧者同工团队祷告

周三
1为我们的属灵生命祷告
2为约书亚团契祷告

周四
1为我们的信心祷告
2为荣美之家祝福祷告

周五
1为广州祝福祷告
2为约书亚团契周六的学习祷告

周六
1为国家祝福祷告
2为主日信息、敬拜及各项服事祷告

周日
1为年轻一代与神对齐、进入命定祷告
2为我们的父母祝福祷告`;
}